package com.san.report.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.san.base.controller.BaseController;
import com.san.base.domain.DictDO;
import com.san.base.service.DictService;
import com.san.common.annotation.Log;
import com.san.common.annotation.ReportLog;
import com.san.common.utils.Constant;
import com.san.common.utils.PageUtils;
import com.san.common.utils.R;
import com.san.common.utils.StringUtils;
import com.san.metadata.domain.BaseNaturalPersonDO;
import com.san.metadata.domain.BusinessDataDO;
import com.san.metadata.domain.DataSourceDO;
import com.san.metadata.domain.ManageTableDO;
import com.san.metadata.service.BaseNaturalPersonService;
import com.san.metadata.service.BusinessDataService;
import com.san.metadata.service.DataSourceService;
import com.san.metadata.service.ManageMetadataService;
import com.san.report.service.NaturalPersonReportService;
import com.san.report.service.ReportRoleService;
import com.san.system.domain.UserDO;
import com.san.system.service.UserService;

/**
 * 自然人信用报告控制器
 * 
 * @author hulp
 *
 */
@RequestMapping("/report/naturalPerson")
@Controller
public class NaturalPersonReportController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(NaturalPersonReportController.class);

	/**
	 * 本功能地址前缀
	 */
	private static final String PREFIX = "report/naturalPerson";

	@Autowired
	BaseNaturalPersonService baseNaturalPersonService;

	@Autowired
	private DictService dictService;

	@Autowired
	NaturalPersonReportService naturalPersonReportService;

	@Autowired
	BusinessDataService businessDataService;

	@Autowired
	ManageMetadataService manageMetadataService;

	@Autowired
	DataSourceService dataSourceService;
	
	@Autowired
	ReportRoleService reportRoleService;
	
	@Autowired
	UserService userService;

	/**
	 * 自然人信用报告列表页
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/view")
	String LegalPersonCreditReport(Model model) {
		return PREFIX + "/view";
	}

	/**
	 * 自然人信用快照列表页
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/viewSnapshot/{naturalPersonId}")
	String viewSnapshot(Model model, @PathVariable String naturalPersonId) {
		model.addAttribute("naturalPersonId", naturalPersonId);
		return PREFIX + "/viewSnapshot";
	}

	/**
	 * 自然人信用快照列表页
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/showSnapshot/{ssId}")
	String showSnapshot(Model model, @PathVariable String ssId) {
		model.addAttribute("ssId", ssId);
		return PREFIX + "/snapshot";
	}

	/**
	 * 自然人查询列表
	 * 
	 * @param params
	 * @return
	 */
	@Log("查询自然人信用报告列表")
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/list")
	@ResponseBody
	public PageUtils findListNaturalPerson(@RequestParam String name, @RequestParam String idCard) {
		List<BaseNaturalPersonDO> list = null;

		idCard = StringUtils.encodeIdCard(idCard);
		try {
			list = baseNaturalPersonService.getNaturalPerson(name, idCard);
			for (BaseNaturalPersonDO i : list) { // 身份证号码 解密脱敏
				i.setIdCard(StringUtils.decodeIdCard(i.getIdCard()));
			}
		} catch (Exception e) {
			logger.error("获取自然人列表出错", e);
		}
		return new PageUtils(list, list.size());
	}

	/**
	 * 自然人信用快照查询列表
	 * 
	 * @param params
	 * @return
	 */
	@Log("查询自然人信用快照列表")
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/listSnapshot")
	@ResponseBody
	public PageUtils listSnapshot(String naturalPersonId, int limit, int offset) {
		List<Map<String, Object>> list = null;
		try {
			list = naturalPersonReportService.listSnapshot(naturalPersonId, limit, offset);
		} catch (Exception e) {
			logger.error("获取快照信息列表出错", e);
		}
		return new PageUtils(list, list.size());
	}

	/**
	 * 自然人信用报告详情页数据
	 * 
	 * @param naturalPersonId 自然人ID
	 * @return
	 */
	@Log("查询法人信用报告")
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/detail")
	@ResponseBody
	R detail(String naturalPersonId) {

		List<DictDO> list = dictService.getByValue(Constant.DICT_NATURAL_PERSON);
		Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
		for (DictDO i : list) {
			Map<String, Object> secondMap = new LinkedHashMap<String, Object>();
			Map<String, Object> requestMap = new LinkedHashMap<String, Object>();
			requestMap.put("parentId", i.getId());
			List<DictDO> requestList = dictService.list(requestMap);
			List<Map<String, Object>> secondResultList = null;
			for (DictDO j : requestList) {
				try {
					secondResultList = naturalPersonReportService.queryBusiDataByNode(j.getId(), naturalPersonId);
					secondMap.put(j.getName(), secondResultList); // 小类，第二层
				} catch (Exception e) {
					logger.error("查询自然人信用报告详细信息出错", e);
				}
			}
			firstMap.put(i.getName(), secondMap); // 大类，最外层

		}

		R r = new R();
		r.put("code", 0);
		r.put("msg", "查询成功");
		r.put("obj", firstMap);

		return r;
	}

	/**
	 * 自然人信用报告列表页
	 * 
	 * @param model
	 * @return
	 */
	@ReportLog(Constant.MODEL_TYPE_NATURAL_PERSON)
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/viewDetail/{naturalPersonId}")
	String viewDetail(Model model, @PathVariable("naturalPersonId") String naturalPersonId) {
		model.addAttribute("naturalPersonId", naturalPersonId);
		return PREFIX + "/report";
	}

	/**
	 * 自然人信用报告列表页
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/printReport/{naturalPersonId}")
	String printReport(Model model, @PathVariable("naturalPersonId") String naturalPersonId) {
		model.addAttribute("naturalPersonId", naturalPersonId);
		return PREFIX + "/printReport";
	}

	/**
	 * 自然人信用快照详情页详细信息
	 * 
	 * @param naturalPersonId 自然人ID
	 * @param busiId          业务元数据ID
	 * @return
	 */
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/linkReport")
	@ResponseBody
	Map<String, Object> linkReport(@RequestParam String naturalPersonId, @RequestParam String busiId) {
		BusinessDataDO businessDataDO = businessDataService.getById(Long.valueOf(busiId));
		ManageTableDO manageTableDO = null;
		DataSourceDO dataSourceDO = null;
		List<String> thList = null;
		try {
			manageTableDO = manageMetadataService.getById(businessDataDO.getTableId());
		} catch (Exception e) {
			logger.error("获取管理元数据信息出错", e);
		}
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());
		} catch (Exception e) {
			logger.error("获取数据源信息出错", e);
		}

		try {
			thList = manageMetadataService.listColumnByIds(businessDataDO.getDetColumnId());
		} catch (Exception e) {
			logger.error("获取表头信息出错", e);
		}

		List<Map<String, Object>> trList = null;
		try {
			trList = naturalPersonReportService.queryReportList(dataSourceDO, naturalPersonId,
					businessDataDO.getBusiSqldet());
		} catch (Exception e) {
			logger.error("获取详细信息出错", e);
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("th", thList);
		resultMap.put("tr", trList);
		return resultMap;
	}

	/**
	 * 获取二维码信息
	 * 
	 * @return
	 */
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/getQRCodeMessage")
	@ResponseBody
	Map<String, Object> getQRCodeMessage() {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		Long userId = getUserId();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		Date date = new Date();
		map.put("userId", userId);
		map.put("time", df.format(date));
		map.put("timeStamp", date.getTime());
		return map;
	}

	/**
	 * 保存快照
	 * 
	 * @param batch   批次号
	 * @param type    快照类型
	 * @param content 快照内容
	 * @return
	 */
	@Log("保存自然人信用快照")
	@RequiresPermissions("report:naturalPerson:view")
	@PostMapping("/snapShot")
	@ResponseBody
	R snapShot(String naturalPersonId, String batch, int type, String content, String QRCode) {
		boolean flag = false;
		try {
			flag = naturalPersonReportService.save(naturalPersonId, batch, type, content, QRCode);
		} catch (Exception e) {
			logger.error("生成快照失败", e);
		}
		if (flag) {
			return R.ok();
		}
		return R.error("生成快照失败");

	}

	/**
	 * 查询快照页面详细信息
	 * 
	 * @param ssId 快照ID
	 * @return
	 */
	@RequiresPermissions("report:naturalPerson:view")
	@PostMapping("/viewSnapShot")
	@ResponseBody
	R viewSnapShot(String ssId) {
		List<Map<String, Object>> list = null;
		try {
			list = naturalPersonReportService.viewSnapShot(ssId);
		} catch (Exception e) {
			logger.error("查询快照失败", e);
		}
		return R.okReturnList(list);
	}
	
	/**
	 * 自然人信用报告详情页数据
	 * 
	 * @param naturalPersonId 自然人ID
	 * @return
	 */
	@Log("查询法人信用报告")
	@RequiresPermissions("report:naturalPerson:view")
	@GetMapping("/detailRole")
	@ResponseBody
	R detailRole(String naturalPersonId) {

		UserDO userDO;
		List<Long> dictIds = null;
		try {
			userDO = (UserDO)userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			dictIds = reportRoleService.dictList(deptId);
		} catch (Exception e) {
			logger.error("获取用户角色失败", e);
			R r = new R();
			r.put("code", 0);
			r.put("msg", "查询失败");
			r.put("obj", "");
			return r;
		}
		
		List<DictDO> list = dictService.getByValue(Constant.DICT_NATURAL_PERSON);
		Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
		for (DictDO i : list) {
			if (dictIds.contains(i.getId())) {
				Map<String, Object> secondMap = new LinkedHashMap<String, Object>();
				Map<String, Object> requestMap = new LinkedHashMap<String, Object>();
				requestMap.put("parentId", i.getId());
				List<DictDO> requestList = dictService.list(requestMap);
				List<Map<String, Object>> secondResultList = null;
				for (DictDO j : requestList) {
					try {
						secondResultList = naturalPersonReportService.queryBusiDataByNode(j.getId(), naturalPersonId);
						secondMap.put(j.getName(), secondResultList); // 小类，第二层
					} catch (Exception e) {
						logger.error("查询自然人信用报告详细信息出错", e);
					}
				}
				firstMap.put(i.getName(), secondMap); // 大类，最外层
			}
		}

		R r = new R();
		r.put("code", 0);
		r.put("msg", "查询成功");
		r.put("obj", firstMap);

		return r;
	}
	
	/**
	 * 自然人信用报告列表页
	 * 
	 * @param model
	 * @return
	 */
	@ReportLog(Constant.MODEL_TYPE_NATURAL_PERSON)
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/viewDetailRole/{naturalPersonId}")
	String viewDetailRole(Model model, @PathVariable("naturalPersonId") String naturalPersonId) {
		model.addAttribute("naturalPersonId", naturalPersonId);
		return PREFIX + "/reportRole";
	}

}
